<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page import="java.io.IOException"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.naming.Context"%>
<%@ page import="javax.naming.InitialContext"%>
<%@ page import="java.sql.SQLException"%>
<%@ page import="java.text.DecimalFormat"%>
<%@ page import="java.net.URLEncoder"%>

<%!
	int paramCount; // Parameter의 갯수
	int fileCount;  // Parameter중 파일의 갯수
    String paramName[];  // Parameter의 Name을 저장하는 String[ParamCount]
    String paramValue[]; // Parameter의 Value를 저장하는 String[ParamCount]
    String paramFileName[];  // 파일의 엘리먼트명을 저장하는 String[fileCount]
    String paramFile[];      // 파일의 이름을 저장하는 String[fileCount]
    int paramFileSize[];     // 파일의 Size을 저장하는 int[fileCount]
    byte paramFileContent[][] = new byte[10][]; // 파일 내용을 담을 byte[fileCount]
    byte tmp_byte[];
    int lengthContent;
    DataInputStream inputStream;
	String file_name;



	private int bindexOf(String tmp,int si)	{

		int i=0,j=0;
		byte tmpb[] = new byte[tmp.length()];
		tmpb = tmp.getBytes();
		for (i=si; i<lengthContent-tmp.length(); i++){
			for (j=0; j<tmp.length(); j++){
				if (tmpb[j]!=tmp_byte[i+j]) break;
			}
			if (j==tmp.length()){
				return (i);
			}
		}
		return (-1);
	}


	private String substringB(int si,int ei) {
		byte tmpb[] = new byte[ei-si];
        String tmps = null;
		for (int i=0; i<ei-si; i++){
			tmpb[i] = tmp_byte[si+i];
		}
        try{
            tmps = new String(tmpb, "UTF-8");
        }catch(Exception e){
            e.printStackTrace();
        }
        return tmps;
	}


	public String getParameter(String pname) {
		for (int i=0; i<paramCount; i++){
			if (paramName[i]!=null && paramName[i].equals(pname)){
				return (paramValue[i]);
			}
		}
		return "";
	}

	public boolean saveFile2(String Directory,String chFileName, byte[] paramFileContent) throws IOException {

		if ( paramFileContent.length > 0){
			FileOutputStream fos = new FileOutputStream(new File("/app/files/person_images/"+chFileName));
			fos.write(paramFileContent);
			fos.close();
		}

		return true;
	}

	private File getTargetFile(String targetDir, String fileName){

		String surfix, prefix,serialSurfix;
		int pointIndex, serial = 0;
		File file;

        pointIndex = fileName.lastIndexOf('.');
        if (pointIndex == -1 || pointIndex == (fileName.length() - 1)) {
            prefix = fileName;
            surfix = null;
        }
        else {
            prefix = fileName.substring(0,pointIndex);
            surfix = fileName.substring(pointIndex + 1);
        }

        fileName = surfix == null ? prefix : prefix + "." + surfix;

        file = new File(targetDir,fileName);

		if(!file.exists()) file_name = paramFile[0];


        while(file.exists()){

            serialSurfix = String.valueOf(serial);
            fileName = surfix == null ? prefix + serialSurfix : prefix + serialSurfix + "." + surfix;

			file_name = fileName;
            file = new File(targetDir,fileName);

            serial ++;
        }
		return file;
	}
%>
<%

		paramName = new String[50];
        paramValue = new String[50];
        paramFileName = new String[10];
        paramFile = new String[10];
        paramFileSize = new int[10];
        paramCount = 0;
        fileCount = 0;
		file_name="";

        int si=0,ei=0;

        try {

            inputStream = new DataInputStream(request.getInputStream());
            lengthContent = Integer.parseInt(request.getHeader("Content-Length"));

                tmp_byte = new byte[lengthContent];
                try {
                    inputStream.readFully(tmp_byte);
                    ei = 0;
                    for (;;){
                        si = bindexOf("form-data; name",ei);
                        if (si==-1){
                            break;
                        }
                        si += 17;
                        ei = bindexOf("\"",si);
                        if (si<ei) {
                            paramName[paramCount] = substringB(si,ei);
                        }
                        else {
                            paramName[paramCount] = "";
                        }

                        if (!substringB(ei+1,ei+2).equals("\r")) {
                            si = ei+13;
                            ei = bindexOf("\"",si);

                            String rfname;
                            if (si<ei){
                                rfname = substringB(si,ei);
                            }
                            else {
                                rfname="";
                            }

                            while (rfname.indexOf("\\")!=-1){
                                rfname = rfname.substring(rfname.indexOf("\\")+1,rfname.length());
                            }

                            paramFile[fileCount] = rfname.trim().replaceAll(" ","");
                            paramFileName[fileCount] = paramName[paramCount];

                            si = bindexOf("\n",ei); si++;
                            si = bindexOf("\n",si); si++;
                            si = bindexOf("\n",si); si++;
                            ei = bindexOf("-----------------------------",si); ei-=2;

                            if(si > ei){ // netscape일때 (by 박경모)
                                ei = si;
                            }
                            paramFileSize[fileCount] = ei-si;
                            paramFileContent[fileCount] = new byte[ei-si];
                            for (int xi=si; xi<ei; xi++) {
                                paramFileContent[fileCount][xi-si] = tmp_byte[xi];
                            }
                            if(paramFileSize[fileCount]>0){  // 파일사이즈가 0이상인 경우만 대상
                                fileCount++;
                            }
                            paramValue[paramCount] = "";
			            }
                        else {
                            si = ei + 5;
                            ei = bindexOf("-----------------------------",si);

                            if (si<ei-2) {
                                paramValue[paramCount] = substringB(si,ei-2);
                            }
                            else {
                                paramValue[paramCount] = "";
                            }
                            ei += 2;
                        }
                        paramCount++;
                    }
                }
                catch(IOException e){
                    paramCount=0;
                    fileCount=0;
				
                }

        } catch (Exception e){
            this.inputStream = null;
	
        }


		int seq = 0;
		String user_id = getParameter("user_id");
		String Directory = "/app/files/person_images/";
		String mil = user_id+".gif";

		saveFile2(Directory, mil, paramFileContent[0]);
		
		Connection conn =   null;
		java.sql.Statement stmt = null;
        java.sql.ResultSet rs = null;    
		java.sql.Blob mySELF_PHOTO_IMAGE = null;

		try{
			Context ctx = new InitialContext();
			Context envContext = (Context)ctx.lookup("java:/comp/env");
			DataSource ds = (DataSource) envContext.lookup("jdbc/portalDB");
			conn = ds.getConnection();
			conn.setAutoCommit(false);

			stmt = conn.createStatement();
			
			String SQL_String 
			  = "SELECT USER_ID, SELF_PHOTO_IMAGE FROM PORTAL_USER WHERE USER_ID = \'"+ user_id+"\' FOR UPDATE";
			rs = stmt.executeQuery(SQL_String);

			while (rs.next()) {
				System.out.println("in the while loop, ID" + rs.getString("USER_ID"));
				mySELF_PHOTO_IMAGE = rs.getBlob("SELF_PHOTO_IMAGE");
			}

			System.out.println("printing mySELF_PHOTO_IMAGE object#########:" + mySELF_PHOTO_IMAGE);

			java.io.OutputStream os = ((oracle.sql.BLOB) mySELF_PHOTO_IMAGE).getBinaryOutputStream();
				 

			System.out.println("Row has been inserted." + paramFileContent[0].length);
			os.write(paramFileContent[0], 0, paramFileContent[0].length);
			os.flush();
			os.close();
			conn.commit();
		} catch (Exception e) {
			try{
				conn.rollback();
			}catch(Exception exx){
				exx.printStackTrace();
			}
            System.out.println("Exception was thrown: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (stmt != null)
                    stmt.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException sqle) {
                System.out.println("SQLException was thrown: " + sqle.getMessage());
            }
        }
  

		if(false){
		%>
		<script>
			alert("실패");
		</script>
		<%
				} else {
				
		%>
		<script>
			opener.document.getElementById('myImg').src = "/images/person_images/<%=user_id%>.gif";
			self.close();
		</script>

		<%
		}
		%>

